package com.jiang.redis.single;

import java.util.Collections;
import java.util.UUID;

import org.junit.Before;
import org.junit.Test;

import redis.clients.jedis.Jedis;

/**
 * 缓存穿透： 访问redis中不存在的key，导致去db中不停的查询 （不存在的key也设置一个空的缓存，加个几分钟的过期时间即可）
 * 缓存击穿： redis中的某个关键key，突然失效，导致大量查询去db中 （用分布式锁来解决，建议用Redisson）
 * 缓存雪崩： 同一时间redis的key同时失效 （数据存入redis中一个固定的时间+一个随机时间即可 1-5分钟的随机时间）
 * @author jiangwz
 * @create 2019/3/7.
 */
public class TestRedis01 {

    private Jedis jedis;

    @Before
    public void before(){
        jedis = new Jedis("localhost",6379);
    }

    @Test
    public void testGet(){
        System.out.println(jedis.get("6666666666"));
    }

    @Test
    public void testSet(){

//        jedis.setex("test01",20, "99999");
        Long count = jedis.incr("count");
        System.out.println(count);
        System.out.println(jedis.incrBy("count1", -100));
        System.out.println(jedis.incr("count1"));
    }

    @Test
    public void testRedis(){
        String key = "testcount";
        System.out.println(jedis.get(key));
        // redis自增
        System.out.println(jedis.incr(key)); // +1
        System.out.println(jedis.incrBy(key, 100));// +100
        System.out.println(jedis.incrBy(key, -100));//-100

        // redis自减
        System.out.println(jedis.decr(key));
        System.out.println(jedis.decrBy(key, 100));
        System.out.println(jedis.decrBy(key, -101));

        String key2 = "hello";
        // redis 追加
        System.out.println(" - " + jedis.append(key2, "nick"));
        System.out.println(jedis.append(key2, " mike"));
        System.out.println(jedis.append(key2, " jekky"));
        System.out.println(jedis.get(key2));

        jedis.expire(key,60);
//        System.out.println(jedis.getSet(key, "200"));
    }

    @Test
    public void testDel(){
        String key = "lua";
        String val = String.valueOf(666);
        jedis.set(key, val);
        System.out.println(jedis.del(key));
    }

    @Test
    public void testLockTimeOut(){
        String lockKey = "lua:lock";
        String token = UUID.randomUUID().toString();
//        jedis.set(lockKey, token);
        System.out.println(jedis.set(lockKey, token, "nx", "EX", 10));
        System.out.println(jedis.set(lockKey, token, "nx", "EX", 10));
        String s = jedis.get(lockKey);
        System.out.println(s);
//        if (s.equals(token)) {
//
//        }

    }

    /**
     * 取到key的同时判断value的值是否
     */
    @Test
    public void testLua(){
        //KEYS[1] ARGV[1]
        String key = "lua";
        String val = String.valueOf(666);
        jedis.set(key, val);
        System.out.println(jedis.get(key));
        String lua  = "if (redis.call('get', KEYS[1]) == ARGV[1]) " +
                "then return redis.call('del',KEYS[1]) else return 0 end";
        jedis.eval(lua, Collections.singletonList(key), Collections.singletonList(val));
        System.out.println(jedis.get(key));

    }

}
